'use client'

import { useState, useRef } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Upload, FileArchive, AlertCircle, CheckCircle } from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'

const uploadSchema = z.object({
  title: z.string().min(2, '工具名称至少需要2个字符').max(100, '工具名称不能超过100个字符'),
  description: z.string().min(10, '描述至少需要10个字符').max(500, '描述不能超过500个字符'),
  categoryId: z.string().min(1, '请选择一个分类'),
  file: z.any().refine((files) => files?.length > 0, '请选择要上传的文件')
})

type UploadForm = z.infer<typeof uploadSchema>

// 静态分类数据
const categories = [
  { id: '1', name: '开发工具', icon: '💻' },
  { id: '2', name: '设计工具', icon: '🎨' },
  { id: '3', name: '效率工具', icon: '⚡' },
  { id: '4', name: '娱乐游戏', icon: '🎮' },
  { id: '5', name: '学习教育', icon: '📚' },
  { id: '6', name: '生活服务', icon: '🏠' }
]

export function ToolUpload() {
  const [isUploading, setIsUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setValue
  } = useForm<UploadForm>({
    resolver: zodResolver(uploadSchema)
  })

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // 验证文件类型
      if (!file.name.endsWith('.zip')) {
        setMessage({
          type: 'error',
          text: '请选择ZIP格式的压缩文件'
        })
        if (fileInputRef.current) {
          fileInputRef.current.value = ''
        }
        return
      }

      // 验证文件大小 (最大50MB)
      if (file.size > 50 * 1024 * 1024) {
        setMessage({
          type: 'error',
          text: '文件大小不能超过50MB'
        })
        if (fileInputRef.current) {
          fileInputRef.current.value = ''
        }
        return
      }

      setSelectedFile(file)
      setValue('file', event.target.files)
      setMessage(null)
    }
  }

  const onSubmit = async (data: UploadForm) => {
    if (!selectedFile) {
      setMessage({ type: 'error', text: '请选择要上传的文件' })
      return
    }

    setIsUploading(true)
    setUploadProgress(0)
    setMessage(null)

    try {
      const formData = new FormData()
      formData.append('file', selectedFile)
      formData.append('title', data.title)
      formData.append('description', data.description)
      formData.append('categoryId', data.categoryId)

      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return prev
          }
          return prev + 10
        })
      }, 200)

      const response = await fetch('/api/admin/tools/upload', {
        method: 'POST',
        body: formData,
      })

      clearInterval(progressInterval)
      setUploadProgress(100)

      const result = await response.json()

      if (!response.ok) {
        throw new Error(result.error || '上传失败')
      }

      setMessage({
        type: 'success',
        text: `工具上传成功！部署路径: ${result.data.deployPath}`
      })
      
      reset()
      setSelectedFile(null)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }

    } catch (error: any) {
      setMessage({
        type: 'error',
        text: error.message || '上传失败，请重试'
      })
    } finally {
      setIsUploading(false)
      setTimeout(() => setUploadProgress(0), 2000)
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Upload className="h-5 w-5" />
            上传HTML工具包
          </CardTitle>
          <CardDescription>
            上传打包好的HTML工具，系统将自动部署并生成访问链接
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {/* 文件上传区域 */}
            <div>
              <label className="block text-sm font-medium mb-2">
                工具文件 (ZIP格式) *
              </label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".zip"
                  onChange={handleFileSelect}
                  className="hidden"
                />
                <div className="space-y-2">
                  <FileArchive className="h-12 w-12 text-gray-400 mx-auto" />
                  {selectedFile ? (
                    <div>
                      <p className="text-sm font-medium text-gray-900">{selectedFile.name}</p>
                      <p className="text-xs text-gray-500">
                        {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                      </p>
                    </div>
                  ) : (
                    <div>
                      <p className="text-sm text-gray-600">点击选择文件或拖拽到此处</p>
                      <p className="text-xs text-gray-500">支持ZIP格式，最大50MB</p>
                    </div>
                  )}
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => fileInputRef.current?.click()}
                  >
                    选择文件
                  </Button>
                </div>
              </div>
              {errors.file && (
                <p className="text-red-500 text-sm mt-1">{errors.file.message}</p>
              )}
            </div>

            {/* 工具信息 */}
            <div>
              <label htmlFor="title" className="block text-sm font-medium mb-2">
                工具名称 *
              </label>
              <input
                {...register('title')}
                type="text"
                id="title"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入工具名称"
              />
              {errors.title && (
                <p className="text-red-500 text-sm mt-1">{errors.title.message}</p>
              )}
            </div>

            <div>
              <label htmlFor="description" className="block text-sm font-medium mb-2">
                工具描述 *
              </label>
              <textarea
                {...register('description')}
                id="description"
                rows={4}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请详细描述这个工具的功能和特点"
              />
              {errors.description && (
                <p className="text-red-500 text-sm mt-1">{errors.description.message}</p>
              )}
            </div>

            <div>
              <label htmlFor="categoryId" className="block text-sm font-medium mb-2">
                工具分类 *
              </label>
              <select
                {...register('categoryId')}
                id="categoryId"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">请选择分类</option>
                {categories.map((category) => (
                  <option key={category.id} value={category.id}>
                    {category.icon} {category.name}
                  </option>
                ))}
              </select>
              {errors.categoryId && (
                <p className="text-red-500 text-sm mt-1">{errors.categoryId.message}</p>
              )}
            </div>

            {/* 上传进度 */}
            {isUploading && (
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>上传进度</span>
                  <span>{uploadProgress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${uploadProgress}%` }}
                  />
                </div>
              </div>
            )}

            {/* 消息提示 */}
            {message && (
              <div className={`p-4 rounded-md flex items-center gap-2 ${
                message.type === 'success' 
                  ? 'bg-green-50 text-green-700 border border-green-200' 
                  : 'bg-red-50 text-red-700 border border-red-200'
              }`}>
                {message.type === 'success' ? (
                  <CheckCircle className="h-4 w-4" />
                ) : (
                  <AlertCircle className="h-4 w-4" />
                )}
                {message.text}
              </div>
            )}

            {/* 提交按钮 */}
            <div className="flex gap-4">
              <Button 
                type="submit" 
                className="flex-1" 
                disabled={isUploading || !selectedFile}
              >
                {isUploading ? '上传中...' : '上传并部署'}
              </Button>
              <Button 
                type="button" 
                variant="outline"
                onClick={() => {
                  reset()
                  setSelectedFile(null)
                  setMessage(null)
                  if (fileInputRef.current) {
                    fileInputRef.current.value = ''
                  }
                }}
              >
                重置
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
